<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2021/3/3 0003 9:20
 * Describe: 企业服务商服务类基类
 */

namespace app\common\server\corp;

use think\exception\ValidateException;

class Base
{
    public function __construct($config = [])
    {
        $this->corpId = $config['corp_id']?? config('queue.corp')['corp_id']?? '';
        $this->secret = $config['secret']?? config('queue.corp')['secret']?? '';
        $this->suiteId = $config['suite_id']?? config('queue.corp')['suite_id']?? '';
        $this->suiteSecret = $config['suite_secret']?? config('queue.corp')['suite_secret']?? '';
        $this->token = $config['token']?? config('queue.corp')['token']?? '';
        $this->encodingAeskey = $config['encoding_aes_key']?? config('queue.corp')['encoding_aes_key']?? '';
        $this->redirectUriInstall = $config['redirect_uri_install']?? config('queue.corp')['redirect_uri_install']?? '';
    }

    /**
     * 获取SuiteTicket
     * @return string
     */
    public function getSuiteTicket(): string
    {
//        return 'yq7uwXV9CYdOC3Cu5Me-RBzOJMLbRoAMfIIjGZfQrkwShLKa9Z3O3oz4LW13bfXk';
        /** @var \app\manage\controller\corp\Callback receive */
        return cache('suiteTicket');
    }

    /**
     * 处理请求返回响应结果
     * @param array $responseResult
     * @throws ValidateException
     * @return
     */
    public function setResponse($responseResult)
    {
        // todo 由于时间关系，此处缺少全局error类处理，预留类如下
        /** @var \app\common\server\corp\ErrorCode */
        if(isset($responseResult['errcode']) && $responseResult['errcode'] != 0){
            check_exception($responseResult['errmsg']?? '');
        }
        return $responseResult;
    }

    /**
     * curl请求
     * @param string $url 请求地址
     * @param array $param 请求数据
     * @param bool $isPost 是否post请求
     * @return
     */
    public function curlFn(string $url = null, array $param = null, bool $isPost = false)
    {
        if ($url === null) return false;
        $culObj = curl_init();
        curl_setopt($culObj, CURLOPT_URL, $url);
        curl_setopt($culObj, CURLOPT_HEADER, false);

        if ($isPost) {
            curl_setopt($culObj, CURLOPT_POST, true);
        } else {
            curl_setopt($culObj, CURLOPT_POST, false);
        }
        if($param){
            $param = json_encode($param, true);
        }
        curl_setopt($culObj, CURLOPT_POSTFIELDS, $param);
        curl_setopt($culObj, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($culObj, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($culObj, CURLOPT_TIMEOUT, 30);
        $data = curl_exec($culObj);
        if ($data === false) {
            //错误信息写入记录日志
            $str = '请求企业微信接口失败 contents:' . curl_error($culObj);
            trace($str, 'error');
            return false;
        }
        curl_close($culObj);
        return json_decode($data, true);
    }

}